package com.mach.platform.security;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.security.web.context.support.SecurityWebApplicationContextUtils;
import org.springframework.security.web.session.HttpSessionCreatedEvent;
import org.springframework.security.web.session.HttpSessionDestroyedEvent;
import org.springframework.security.web.session.HttpSessionEventPublisher;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * useless
 * @author Anonymous-----使用内置 tomcat后，在springboot的配置文件配置后，这里就不需要了
 *
 * @Description:  重写 HttpSessionEventPublisher  ，并且添加到Linstener中，因为server.session.timeout无法注入
 * 				  在创建session的方法中，把配置中的 过期时间设置进去。
 * 				  其他代码跟 原来HttpSessionEventPublisher 一样。
 * @Package: com.mach.platform.security
 * @Time create on 2017/11/29 22:49
 */
public class CuHttpSessionEventPublisher implements HttpSessionListener {

	private static final String log_NAME = HttpSessionEventPublisher.class.getName();


	ApplicationContext getContext(ServletContext servletContext) {
		return SecurityWebApplicationContextUtils.findRequiredWebApplicationContext(servletContext);
	}

	/**
	 * Handles the HttpSessionEvent by publishing a {@link HttpSessionCreatedEvent} to the
	 * application appContext.
	 *
	 * @param event HttpSessionEvent passed in by the container
	 */
	@Override
	public void sessionCreated(HttpSessionEvent event) {
		HttpSessionCreatedEvent e = new HttpSessionCreatedEvent(event.getSession());
		Log log = LogFactory.getLog(log_NAME);

		if (log.isDebugEnabled()) {
			log.debug("Publishing event: " + e);
		}

		//设置session过期时间
		event.getSession().setMaxInactiveInterval(60);

		getContext(event.getSession().getServletContext()).publishEvent(e);
	}

	/**
	 * Handles the HttpSessionEvent by publishing a {@link HttpSessionDestroyedEvent} to
	 * the application appContext.
	 *
	 * @param event The HttpSessionEvent pass in by the container
	 */
	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
		HttpSessionDestroyedEvent e = new HttpSessionDestroyedEvent(event.getSession());
		Log log = LogFactory.getLog(log_NAME);

		if (log.isDebugEnabled()) {
			log.debug("Publishing event: " + e);
		}

		getContext(event.getSession().getServletContext()).publishEvent(e);
	}

}
